﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Supplier;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using MediatR;
using static Google.Protobuf.Reflection.SourceCodeInfo.Types;

namespace BasicInformation.ApiWrite.Application.Handler.Supplier
{
    public class UpdateSupplierHandler : IRequestHandler<UpdateSupplierCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateSupplierHandler> logger;

        public UpdateSupplierHandler(DatabaseContext db,IMapper mapper,ILogger<UpdateSupplierHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateSupplierCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var supplier = db.SqlSugar.Queryable<SupplierModel>().Where(x => x.SupplierId == request.SupplierId).First();
            //if (supplier == null)
            //{
            //    result.Msg = "你要修改的用户不存在";
            //    result.Code = ApiEnum.Fail;
            //    logger.LogError(result.Msg);
            //    return Task.FromResult(result);
            //}
            //var model = supplierRepo.GetAll().Where(x => x.SupplierName == request.SupplierName).Count();
            //if (model == 1)
            //{
            //    result.Msg = "供应商名称已存在";
            //    result.Code = ApiEnum.Fail;
            //    logger.LogError(result.Msg);
            //    return Task.FromResult(result);
            //}
            supplier = mapper.Map(request, supplier);
            int r = await db.SqlSugar.Updateable(supplier).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "供应商管理修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "供应商管理修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
